<template>
	<div :class="['cover_select_wrapper', { 'is-disabled': compDisabled }]">
		<el-upload class="upload" :action="uploadUrl" :disabled="compDisabled" v-bind="uploadConfig"></el-upload>
		<template v-if="!checkedCover && type === '100'">
			<span class="el-icon-plus" @click="handleClickUpload()" v-loading="uploadLoading"></span>
		</template>
		<template v-else>
			<el-image ref="image" :src="checkedCover" :preview-src-list="[checkedCover]"></el-image>
			<el-button-group>
				<template v-if="type === '100'">
					<el-button type="text" icon="el-icon-edit" @click="handleClickUpload()"></el-button>
				</template>
				<el-button type="text" icon="el-icon-search" @click="handlePreviewImage()"></el-button>
				<template v-if="type === '100'">
					<el-button type="text" icon="el-icon-delete" @click="handleDeleteUpload()"></el-button>
				</template>
			</el-button-group>
		</template>
		<div v-if="type !== '100'" class="swiper" ref="swiper">
			<el-radio-group class="swiper-wrapper" v-model="checkedId" aria-hidden>
				<el-radio class="swiper-slide" v-for="(item, index) in coverListData" :key="index" :label="item.id">
					<i class="el-icon-check-mark"></i>
					<img :src="item.imageUrl | attrAddrFilter" />
				</el-radio>
			</el-radio-group>
		</div>
	</div>
</template>

<script>
import lodash from 'lodash';
import 'swiper/swiper-bundle.min.css';
import Swiper from 'swiper/swiper-bundle';
import { getAttachList } from '@/api/global';
export default {
	props: {
		type: { type: String, default: '' },
		value: { type: String, default: '' },
		initValue: { type: String, default: '' },
		disabled: { type: Boolean, default: false }
	},
	inject: { elForm: { default: '' } },
	data() {
		const uploadAction = `${!window.baseUrl ? process.env.VUE_APP_BASEURL : window.baseUrl}`;
		return {
			isFirst: true,
			mySwiper: null,
			uploadUrl: `${uploadAction}tbSysAttachment/upload`,
			checkedId: this.value,
			coverListData: [],
			uploadConfig: {
				limit: 1,
				ref: 'upload',
				showFileList: false,
				accept: '.jpg,.jpeg,.png,.gif',
				data: { type: 1, showType: 1, category: '-1' },
				headers: { Authorization: this.$local.get('token') },
				beforeUpload: this.handleBeforeUpload,
				onSuccess: this.handleUploadSuccess,
				onChange: this.handleUploadChange
			},
			uploadLoading: false
		};
	},
	filters: {
		attrAddrFilter(input) {
			return window.staticPath + input;
		}
	},
	computed: {
		checkedCover() {
			let list = this.coverListData;
			let info = list.find((item) => item.id === this.checkedId);
			return !info ? '' : `${window.staticPath}${info.attrAddr}`;
		},
		compDisabled() {
			return this.disabled || (this.elForm || {}).disabled;
		}
	},
	watch: {
		value(val) {
			this.checkedId = val;
		},
		checkedId(val) {
			this.$emit('input', val);
		},
		type: {
			async handler(val) {
				if (!val) return false;
				this.coverListData = [];
				this.checkedId = this.checkedId;
				if (val === '100') {
					await this.getUploadCoverData(this.value);
				} else {
					await this.getCoverListData(val);
					this.$nextTick(() => this.initSwiper());
				}
			}
			// immediate: true
		}
	},
	methods: {
		initSwiper() {
			if (this.mySwiper) this.mySwiper.destroy();
			this.mySwiper = new Swiper(this.$refs['swiper'], {
				slidesPerView: 5,
				grid: { rows: 2 },
				spaceBetween: 10,
				allowTouchMove: !this.compDisabled,
				navigation: {
					nextEl: '.swiper-button-next',
					prevEl: '.swiper-button-prev'
				}
			});
		},

		async getUploadCoverData(id) {
			if (!this.isFirst) {
				this.checkedId = '';
			} else {
				let result = await this.$store.dispatch('getFileUrl', id);
				this.coverListData = [{ id, imageUrl: result }];
				this.isFirst = false;
			}
		},

		async getCoverListData(category) {
			let params = { page: 1, limit: 9999, type: 5, category };
			let result = await getAttachList(params).then((res) => res.data);
			if (result.code === '0') {
				let datas = result.data || [];
				if (!this.initValue || this.initValue === '-1') {
					this.checkedId = datas[0].id;
				}
				this.coverListData = lodash.pick(datas, ['id', 'attrAddr']);
			}
		},

		handleClickUpload() {
			this.$refs['upload'].$refs['upload-inner'].handleClick();
		},

		handlePreviewImage() {
			this.$refs['image'].clickHandler();
		},

		handleDeleteUpload() {
			this.checkedId = '';
		},

		handleBeforeUpload(file) {
			this.uploadLoading = true;
		},

		handleUploadSuccess(res, file, fileList) {
			this.uploadLoading = false;
			this.$refs['upload'].clearFiles();
			if (res.code === '0') {
				let datas = res.data || [];
				this.checkedId = !datas[0] ? '' : datas[0].id;
				this.coverListData = datas.map((n) => {
					return { id: n.id, imageUrl: n.originalAddr };
				});
			}
		},

		async handleUploadChange(file, fileList) {
			// this.coverImage = await fileToBlob(file.raw);
		}
	}
};
</script>

<style lang="scss" scoped>
@import './baseinfo.scss';
</style>
